package com.xfly.app.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.ptmall.app.BuildConfig;
import com.ptmall.app.R;
import com.ptmall.app.base.BaseMvpActivity;
import com.ptmall.app.net.api.ApiDataRepository;
import com.ptmall.app.net.base.ApiNetResponse;
import com.ptmall.app.utils.GlideUtil;
import com.ptmall.app.view.PullToRefreshLayout;
import com.ptmall.app.view.PullableListView;
import com.ptmall.app.view.TitleBarView;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xfly.app.adapter.KcAdapter;
import com.xfly.app.bean.KcBean;
import com.xfly.app.bean.KcggBean;
import com.xfly.app.bean.QbBean;
import com.xfly.app.bean.UserBean;
import com.xfly.app.ui.dialog.KcDialog;
import com.xfly.app.wxapi.ImageUtil;
import com.xfly.app.wxapi.SharePlatform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class KcActivity extends BaseMvpActivity {

    View view1,view2;
    TextView sj,xj;
    PullToRefreshLayout refresh_view;
    PullableListView listview;
    TitleBarView title_bar;
    ApiDataRepository apiDataRepository = ApiDataRepository.getInstance();

    KcAdapter kcAdapter;

    List<KcBean> list = new ArrayList<>();

    int page = 1;

    String status = "2";
    UserBean mUserBean;
    private static final int WX_THUMB_SIZE = 120;
    KcDialog kcDialog;
    private Bitmap bitmap;//图片 缩略图 Web分享 视频分享 音乐分享 图片分享

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setView(R.layout.activity_kc);
        mIWXAPI = WXAPIFactory.createWXAPI(this, BuildConfig.WEIXIN_APP_ID, false);
        mIWXAPI.registerApp(BuildConfig.WEIXIN_APP_ID);

        apiDataRepository.myInfo(null, new ApiNetResponse<UserBean>() {
            @Override
            public void onSuccess(UserBean data) {
                mUserBean = data;
            }
        });
    }

    @Override
    public void initViews() {
        view1 = findViewById(R.id.view1);
        title_bar = findViewById(R.id.title_bar);
        view2 = findViewById(R.id.view2);
        sj = findViewById(R.id.sj);
        xj = findViewById(R.id.xj);
        refresh_view = findViewById(R.id.refresh_view);
        listview = findViewById(R.id.listview);
        title_bar.setText("库存商品");
        title_bar.setOnTitleBarClickListener(new TitleBarView.TitleBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        sj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view1.setVisibility(View.VISIBLE);
                view2.setVisibility(View.INVISIBLE);
                sj.setTextColor(0xFFE6212A);
                xj.setTextColor(0xff666666);
                status = "2";
                page = 1;
                kcAdapter.setStatus(status);
                getlist();
            }
        });

        xj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view2.setVisibility(View.VISIBLE);
                view1.setVisibility(View.INVISIBLE);
                xj.setTextColor(0xFFE6212A);
                sj.setTextColor(0xff666666);
                status = "1";
                page = 1;
                kcAdapter.setStatus(status);
                getlist();

            }
        });

        kcAdapter = new KcAdapter(getContext(),list);
        listview.setAdapter(kcAdapter);
        kcAdapter.setClick(new KcAdapter.Click() {
            @Override
            public void Click(int position) {
                getGG(list.get(position).id);
            }

            @Override
            public void Click2(int position) {
                sxj(list.get(position).id);
            }

            @Override
            public void Click3(int position) {
                GlideUtil.showImg(KcActivity.this, list.get(position).cover, null, bmt -> {//下载成功 后替换
                    if (null != bmt) {
                        bitmap = bmt;
                    }
                    //压缩 微信分享时 bitMap 不能太大
                    if (bitmap != null && bitmap.getByteCount() > 0) {
                        bitmap = ImageUtil.zoomBitmap(bitmap, 48, 48);
                    }
                    shareWeb(SharePlatform.WX, list.get(position).name, list.get(position).intro, "" +
                            "http://xifengapp.com/cn/goods/detail/id/"+list.get(position).id+"/referrer/"+mUserBean.getId()+".html"
                            , bitmap, KcActivity.this);
                });
            }
        });
        getlist();
    }

    @Override
    public void initEvents() {

        refresh_view.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                page = 1;
                getlist();
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                page++;
                getlist();
            }
        });
    }

    private void getlist(){
        Map<String,String> map = new HashMap<>();
        map.put("page",page+"");
        map.put("status",status);
        apiDataRepository.kclist(map, new ApiNetResponse<List<KcBean>>() {
            @Override
            public void onSuccess(List<KcBean> data) {
                if(refresh_view!=null){
                    refresh_view.refreshFinish(PullToRefreshLayout.SUCCEED);
                    refresh_view.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                }
                if(page == 1){
                    list.clear();
                }
                list.addAll(data);
                kcAdapter.pushData(list);
            }

            @Override
            public void onFaile(String info, List<KcBean> data, Throwable throwable) {
                super.onFaile(info, data, throwable);
                if(refresh_view!=null){
                    refresh_view.refreshFinish(PullToRefreshLayout.SUCCEED);
                    refresh_view.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                    list.clear();
                    kcAdapter.pushData(list);
                }
            }
        });
    }

    private void sxj(String id){
        Map<String,String> map = new HashMap<>();
        map.put("goods_id",id);
        if(status.equals("2")){
            map.put("status","0");
        }else {
            map.put("status","1");
        }
        apiDataRepository.sxj(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                page = 1;
                getlist();
            }
        });
    }

    private void getGG(String id){
        Map<String,String> map = new HashMap<>();
        map.put("goods_id",id);
        apiDataRepository.getKcGG(map, new ApiNetResponse<List<KcggBean>>(getContext()) {
            @Override
            public void onSuccess(List<KcggBean> data) {
                kcDialog = new KcDialog(getContext(),data);
                kcDialog.setonclick(new KcDialog.Onclick() {
                    @Override
                    public void Yes(String pass) {
                        setGG(pass,id);
                    }
                });
                kcDialog.show();
            }
        });
    }

    private void setGG(String gg,String id){

        Map<String,String> map = new HashMap<>();
        map.put("goods_id",id);
        if(!TextUtils.isEmpty(gg)){
            map.put("stock",gg.substring(0,gg.length()-1));
        }
        apiDataRepository.setGG(map, new ApiNetResponse<Object>(getContext()) {
            @Override
            public void onSuccess(Object data) {
                showMsg("设置成功");
                page = 1;
                getlist();
            }
        });

    }

    private IWXAPI mIWXAPI;

    public void shareWeb(int platform, String title, String content, String url, Bitmap bitmap,
                         Context activity) {
        //初始化一个WXWebpageObject对象，填写分享的网页地址
        WXWebpageObject webObject = new WXWebpageObject();
        webObject.webpageUrl=url;
        //对象初始化一个WXMediaMessage对象
        WXMediaMessage message = new WXMediaMessage(webObject);
        message.title = title;//标题
        message.description = content;//描述
        if(null==bitmap){
            bitmap= BitmapFactory.decodeResource(activity.getResources(),R.mipmap.ic_launcher );
        }
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bitmap, WX_THUMB_SIZE, WX_THUMB_SIZE, true);
//        bitmap.recycle();
        message.thumbData = ImageUtil.bitmap2Bytes(thumbBmp);
        sendMessage(platform, message, buildTransaction("webpage"));
    }


    private void sendMessage(int platform, WXMediaMessage message, String transaction) {
        //构造一个RQ transaction用户标示类型
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = transaction;
        req.message = message;
        req.scene = platform == SharePlatform.WX_TIMELINE ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        mIWXAPI.sendReq(req);
    }

    private String buildTransaction(String type) {
        return System.currentTimeMillis() + type;
    }


}
